package br.univas.dao;



import java.util.ArrayList;
import java.util.List;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;

import br.edu.univas.locadoragraphtcc.database.Connection;
import br.univas.to.ActorTO;

public class ActorDAO {
	private static final String INDEXKEY = "actor";
	private static final String ACTORKEY = "name";
	private Connection conn;

	public ActorDAO() {
		conn = Connection.getInstance();
	}
	
	public boolean saveActorGraph(ActorTO actor){
		long start = System.currentTimeMillis();
		GraphDatabaseService graph = conn.newGraphDatabase();
		
		Index<Node> index = graph.index().forNodes(INDEXKEY);
		Node node = index.get(ACTORKEY, actor.getName().toLowerCase()).getSingle();
		
		if (node == null) {
			Transaction tx = graph.beginTx();
			
			try {
				node = graph.createNode();
				node.setProperty(ACTORKEY, actor.getName().toLowerCase());
				node.setProperty("gender", actor.getGender().toLowerCase());
				index.add(node, ACTORKEY, actor.getName().toLowerCase());
				tx.success();
			} catch (Exception e) {
				System.out.println("Erro" + e);
				tx.failure();
			} finally {
				tx.finish();
			}
			graph.shutdown();
			double total = System.currentTimeMillis() - start;
			
			System.out.println("Ator cadastrado com sucesso. Operação feita em " + total/1000 + " segundos");
			
			return true;
		}
		graph.shutdown();
		double total = System.currentTimeMillis() - start;
		
		System.out.println("Ator já foi cadastrado. Operação feita em " + total/1000 + " segundos");
		return false;
	}
	
	public List<String> getAllActors(){
		List<String> actors = new ArrayList<>();
		long start = System.currentTimeMillis();
		GraphDatabaseService graph = conn.newGraphDatabase();
		Index<Node> index = graph.index().forNodes(INDEXKEY);
		Iterable<Node> nodes = index.query(ACTORKEY, "*");
		for (Node node : nodes) {
	
			actors.add((String) node.getProperty(ACTORKEY));			
		}
		double total = System.currentTimeMillis() - start;
		System.out.println("Time" + total/1000 );
		return actors;
	}
}